package cn.com.winning.ecare.common;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import yxt.push.org.androidpn.client.ServiceManager;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.WindowManager;
import cn.com.winning.ecare.model.UserRecords;

import com.easemob.chat.ConnectionListener;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.OnNotificationClickListener;
import com.easemob.chatuidemo.activity.ChatActivity;
import com.easemob.chatuidemo.activity.MainActivity;
import com.easemob.chatuidemo.db.DbOpenHelper;
import com.easemob.chatuidemo.db.UserDao;
import com.easemob.chatuidemo.domain.User;
import com.easemob.chatuidemo.utils.PreferenceUtils;

public class MyApplication extends Application
{

	private String account;//账号
	private String syxh;//首页序号
	private String ryrq;//入院日期
	private List<Map<String, Object>>[] list_gwc;
	private List<Integer>[] list_position;
	private String gnlb;
	private String hzxm;//患者姓名
	private String yycontent;
	private String yydm;//医院代码
	private String yymc;//医院名称
	private String deviceId;
	private String sex;//性别
	private String sfzh;//身份证号
	private String sjh;//手机号
	private String dqdm;// 地区代码
	private String dqmc;//地区名称
	private UserRecords userRecords;
	private String version;
	private List<Activity> activityList = new LinkedList<Activity>();
	private String devicenumber;
	private String familysfzhs;//记录一个账号下绑定多个家庭成员身份证号
	public ServiceManager serviceManager;
	private String zhstate;
	private String activeFlag;
	private String currentuerid;//删除家庭成员时用
	private String mzpayflag;//门诊支付标志
	private String zypayflag;//住院支付标志
	private String ghpayflag;//挂号支付标志
	private String jzhflag;//注册时是否需要就诊卡标志
	private String jzcard;//就诊卡号
	private String memberid;//家庭成员id
	private String messageflag;//短信验证开启标志
	
	private String startDate;
	private String endDate;

	private WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();

	//环信

	public static Context applicationContext;
	private static MyApplication instance;
	// login user name
	public final String PREF_USERNAME = "username";
	private String userName = null;
	// login password
	private static final String PREF_PWD = "pwd";
	private String password = null;
	private Map<String, User> contactList;
	//////////////////
	
	@Override
	public void onCreate()
	{
		// TODO Auto-generated method stub
		super.onCreate();
		
		//环信/////////////

		int pid = android.os.Process.myPid();
		String processAppName = getAppName(pid);
		// 如果使用到百度地图或者类似启动remote service的第三方库，这个if判断不能少
		if (processAppName == null || processAppName.equals("")) {
			// workaround for baidu location sdk
			// 百度定位sdk，定位服务运行在一个单独的进程，每次定位服务启动的时候，都会调用application::onCreate
			// 创建新的进程。
			// 但环信的sdk只需要在主进程中初始化一次。 这个特殊处理是，如果从pid 找不到对应的processInfo
			// processName，
			// 则此application::onCreate 是被service 调用的，直接返回
			return;
		}
		applicationContext = this;
		instance = this;
		// 初始化环信SDK,一定要先调用init()
		Log.d("EMChat Demo", "initialize EMChat SDK");
		EMChat.getInstance().init(applicationContext);
		// debugmode设为true后，就能看到sdk打印的log了
		EMChat.getInstance().setDebugMode(true);

		// 获取到EMChatOptions对象
		EMChatOptions options = EMChatManager.getInstance().getChatOptions();
		// 默认添加好友时，是不需要验证的，改成需要验证
		options.setAcceptInvitationAlways(false);
		// 设置收到消息是否有新消息通知，默认为true
		options.setNotificationEnable(PreferenceUtils.getInstance(applicationContext).getSettingMsgNotification());
		// 设置收到消息是否有声音提示，默认为true
		options.setNoticeBySound(PreferenceUtils.getInstance(applicationContext).getSettingMsgSound());
		// 设置收到消息是否震动 默认为true
		options.setNoticedByVibrate(PreferenceUtils.getInstance(applicationContext).getSettingMsgVibrate());
		// 设置语音消息播放是否设置为扬声器播放 默认为true
		options.setUseSpeaker(PreferenceUtils.getInstance(applicationContext).getSettingMsgSpeaker());
		// 设置notification消息点击时，跳转的intent为自定义的intent
		options.setOnNotificationClickListener(new OnNotificationClickListener() {

			@Override
			public Intent onNotificationClick(EMMessage message) {
				Intent intent = new Intent(applicationContext, ChatActivity.class);
				ChatType chatType = message.getChatType();
				if (chatType == ChatType.Chat) { // 单聊信息
					intent.putExtra("userId", message.getFrom());
					intent.putExtra("chatType", ChatActivity.CHATTYPE_SINGLE);
				} else { // 群聊信息
							// message.getTo()为群聊id
					intent.putExtra("groupId", message.getTo());
					intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
				}
				return intent;
			}
		});
		// 设置一个connectionlistener监听账户重复登陆
		EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
		// 取消注释，app在后台，有新消息来时，状态栏的消息提示换成自己写的
		// options.setNotifyText(new OnMessageNotifyListener() {
		//
		// @Override
		// public String onNewMessageNotify(EMMessage message) {
		// //可以根据message的类型提示不同文字，demo简单的覆盖了原来的提示
		// return "你的好基友" + message.getFrom() + "发来了一条消息哦";
		// }
		//
		// @Override
		// public String onLatestMessageNotify(EMMessage message, int
		// fromUsersNum, int messageNum) {
		// return fromUsersNum + "个基友，发来了" + messageNum + "条消息";
		// }
		// });

//		MobclickAgent.onError(applicationContext);
		///////////////
		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		userRecords = new UserRecords();
		userRecords.setDeviceid(tm.getDeviceId());
		userRecords.setPhonenum(tm.getLine1Number());
		userRecords.setNetworktype(String.valueOf(tm.getNetworkType()));
		userRecords.setPhonetype(String.valueOf(tm.getPhoneType()));
		userRecords.setSimoperator(tm.getSimOperator());
		userRecords.setSimoperatorname(tm.getSimOperatorName());
		userRecords.setSubscriberid(tm.getSubscriberId());
		userRecords.setSdk(android.os.Build.VERSION.SDK);
		userRecords.setModel(android.os.Build.MODEL);
		userRecords.setRelease(android.os.Build.VERSION.RELEASE);
	}
	
	
	private String getAppName(int pID) {
		String processName = null;
		ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
		List l = am.getRunningAppProcesses();
		Iterator i = l.iterator();
		PackageManager pm = this.getPackageManager();
		while (i.hasNext()) {
			ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
			try {
				if (info.pid == pID) {
					CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
					// Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
					// info.processName +"  Label: "+c.toString());
					// processName = c.toString();
					processName = info.processName;
					return processName;
				}
			} catch (Exception e) {
				// Log.d("Process", "Error>> :"+ e.toString());
			}
		}
		return processName;
	}

	// 添加Activity到容器中
	public void addActivity(Activity activity)
	{
		activityList.add(activity);
	}

	// 遍历所有Activity并finish

	public void exit()
	{

		for (Activity activity : activityList)
		{
			activity.finish();
		}

		System.exit(0);

	}
	
	
	class MyConnectionListener implements ConnectionListener {
		@Override
		public void onReConnecting() {
		}

		@Override
		public void onReConnected() {
		}

		@Override
		public void onDisConnected(String errorString) {
			if (errorString != null && errorString.contains("conflict")) {
				Intent intent = new Intent(applicationContext, MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra("conflict", true);
				startActivity(intent);
			}

		}

		@Override
		public void onConnecting(String progress) {

		}

		@Override
		public void onConnected() {
		}
	}
	
	
	public static MyApplication getInstance() {
		return instance;
	}

	/**
	 * 获取当前登陆用户名
	 * 
	 * @return
	 */
	public String getUserName() {
		if (userName == null) {
			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
			userName = preferences.getString(PREF_USERNAME, null);
		}
		return userName;
	}

	/**
	 * 获取密码
	 * 
	 * @return
	 */
	public String getPassword() {
		if (password == null) {
			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
			password = preferences.getString(PREF_PWD, null);
		}
		return password;
	}

	/**
	 * 设置用户名
	 * 
	 * @param user
	 */
	public void setUserName(String username) {
		if (username != null) {
			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
			SharedPreferences.Editor editor = preferences.edit();
			if (editor.putString(PREF_USERNAME, username).commit()) {
				userName = username;
			}
		}
	}

	/**
	 * 设置密码 下面的实例代码 只是demo，实际的应用中需要加password 加密后存入 preference 环信sdk
	 * 内部的自动登录需要的密码，已经加密存储了
	 * 
	 * @param pwd
	 */
	public void setPassword(String pwd) {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
		SharedPreferences.Editor editor = preferences.edit();
		if (editor.putString(PREF_PWD, pwd).commit()) {
			password = pwd;
		}
	}

	/**
	 * 退出登录,清空数据
	 */
	public void logout() {
		// 先调用sdk logout，在清理app中自己的数据
		EMChatManager.getInstance().logout();
		DbOpenHelper.getInstance(applicationContext).closeDB();
		// reset password to null
		setPassword(null);
		setContactList(null);

	}
	
	
	/**
	 * 获取内存中好友user list
	 * 
	 * @return
	 */
	public Map<String, User> getContactList() {
		if (getUserName() != null && contactList == null) {
			UserDao dao = new UserDao(applicationContext);
			// 获取本地好友user list到内存,方便以后获取好友list
			contactList = dao.getContactList();
		}
		return contactList;
	}
	
	/**
	 * 设置好友user list到内存中
	 * 
	 * @param contactList
	 */
	public void setContactList(Map<String, User> contactList) {
		this.contactList = contactList;
	}

	public void setStrangerList(Map<String, User> List) {

	}
	

	public List<Integer>[] getList_position()
	{
		return list_position;
	}

	public void setList_position(List<Integer>[] list_position)
	{
		this.list_position = list_position;
	}

	public List<Map<String, Object>>[] getList_gwc()
	{
		return list_gwc;
	}

	public void setList_gwc(List<Map<String, Object>>[] list_gwc)
	{
		this.list_gwc = list_gwc;
	}

	public String getRyrq()
	{
		return ryrq;
	}

	public void setRyrq(String ryrq)
	{
		this.ryrq = ryrq;
	}

	public String getSyxh()
	{
		return syxh;
	}

	public void setSyxh(String syxh)
	{
		this.syxh = syxh;
	}

	public WindowManager.LayoutParams getMywmParams()
	{
		return wmParams;
	}

	public String getAccount()
	{
		return account;
	}

	public void setAccount(String account)
	{
		this.account = account;
	}

	public String getGnlb()
	{
		return gnlb;
	}

	public void setGnlb(String gnlb)
	{
		this.gnlb = gnlb;
	}

	public String getHzxm()
	{
		return hzxm;
	}

	public void setHzxm(String hzxm)
	{
		this.hzxm = hzxm;
	}

	public String getYycontent()
	{
		return yycontent;
	}

	public void setYycontent(String yycontent)
	{
		this.yycontent = yycontent;
	}

	public String getYydm()
	{
		return yydm;
	}

	public void setYydm(String yydm)
	{
		this.yydm = yydm;
	}

	public String getYymc()
	{
		return yymc;
	}

	public void setYymc(String yymc)
	{
		this.yymc = yymc;
	}

	public String getDeviceId()
	{
		return deviceId;
	}

	public void setDeviceId(String deviceId)
	{
		this.deviceId = deviceId;
	}

	public String getSex()
	{
		return sex;
	}

	public void setSex(String sex)
	{
		this.sex = sex;
	}

	public String getSfzh()
	{
		return sfzh;
	}

	public void setSfzh(String sfzh)
	{
		this.sfzh = sfzh;
	}

	public String getSjh()
	{
		return sjh;
	}

	public void setSjh(String sjh)
	{
		this.sjh = sjh;
	}

	public String getDqdm()
	{
		return dqdm;
	}

	public void setDqdm(String dqdm)
	{
		this.dqdm = dqdm;
	}

	public String getDqmc()
	{
		return dqmc;
	}

	public void setDqmc(String dqmc)
	{
		this.dqmc = dqmc;
	}

	public String getVersion()
	{
		return version;
	}

	public void setVersion(String version)
	{
		this.version = version;
	}
	
	public String getDevicenumber() {
		return devicenumber;
	}

	public void setDevicenumber(String devicenumber) {
		this.devicenumber = devicenumber;
	}

	public String getFamilysfzhs() {
		return familysfzhs;
	}

	public void setFamilysfzhs(String familysfzhs) {
		this.familysfzhs = familysfzhs;
	}

	public String getZhstate() {
		return zhstate;
	}

	public void setZhstate(String zhstate) {
		this.zhstate = zhstate;
	}

	public String getActiveFlag() {
		return activeFlag;
	}

	public void setActiveFlag(String activeFlag) {
		this.activeFlag = activeFlag;
	}


	public UserRecords getUserRecords()
	{
		return userRecords;
	}

	public void setUserRecords(UserRecords userRecords)
	{
		this.userRecords = userRecords;
	}

	public ServiceManager getServiceManager()
	{
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager)
	{
		this.serviceManager = serviceManager;
	}

	public String getCurrentuerid() {
		return currentuerid;
	}

	public void setCurrentuerid(String currentuerid) {
		this.currentuerid = currentuerid;
	}

	public String getMzpayflag() {
		return mzpayflag;
	}

	public void setMzpayflag(String mzpayflag) {
		this.mzpayflag = mzpayflag;
	}

	public String getZypayflag() {
		return zypayflag;
	}

	public void setZypayflag(String zypayflag) {
		this.zypayflag = zypayflag;
	}

	public String getGhpayflag() {
		return ghpayflag;
	}

	public void setGhpayflag(String ghpayflag) {
		this.ghpayflag = ghpayflag;
	}

	public String getStartDate()
	{
		return startDate;
	}

	public void setStartDate(String startDate)
	{
		this.startDate = startDate;
	}

	public String getEndDate()
	{
		return endDate;
	}

	public void setEndDate(String endDate)
	{
		this.endDate = endDate;
	}

	public String getJzhflag() {
		return jzhflag;
	}

	public void setJzhflag(String jzhflag) {
		this.jzhflag = jzhflag;
	}

	public String getJzcard() {
		return jzcard;
	}

	public void setJzcard(String jzcard) {
		this.jzcard = jzcard;
	}

	public String getMemberid() {
		return memberid;
	}

	public void setMemberid(String memberid) {
		this.memberid = memberid;
	}

	public String getMessageflag() {
		return messageflag;
	}

	public void setMessageflag(String messageflag) {
		this.messageflag = messageflag;
	}
	
}
